﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Windows.Threading;

namespace Phone.Framework.Threads
{
    public class DelayTimer
    {
        DispatcherTimer _gapValidateTimer;

        private ObservableCollection<object> ListenList { get; set; }

        public DelayTimer()
        {
            ListenList = new ObservableCollection<object>();
            ListenList.CollectionChanged += new NotifyCollectionChangedEventHandler(ListenListCollectionChanged);
        }

        void ListenListCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    ReStart();
                    break;
                case NotifyCollectionChangedAction.Remove:
                    break;
                case NotifyCollectionChangedAction.Replace:
                    break;
                case NotifyCollectionChangedAction.Reset:
                    break;

            }
        }

        public void ReStart()
        {
            _gapValidateTimer.Stop();
            _gapValidateTimer.Start();
        }

        public void AddObj(object obj)
        {
            ListenList.Add(obj);
        }

        public void InitInvoke(double second, Action action)
        {
            if (_gapValidateTimer == null && second > 0)
            {
                _gapValidateTimer = new DispatcherTimer();
                _gapValidateTimer.Interval = TimeSpan.FromSeconds(second);
                _gapValidateTimer.Tick += delegate
                {
                    action();
                    _gapValidateTimer.Stop();
                };
            }
        }

        public void InitInvoke(double second, Action<object> action)
        {
            if (_gapValidateTimer == null && second > 0)
            {
                _gapValidateTimer = new DispatcherTimer();
                _gapValidateTimer.Interval = TimeSpan.FromSeconds(second);
                _gapValidateTimer.Tick += delegate
                {
                    if (ListenList.Count == 0)
                        _gapValidateTimer.Stop();
                    action(ListenList[ListenList.Count - 1]);
                    _gapValidateTimer.Stop();
                    ListenList.Clear();
                };
            }
        }
    }
}
